CycleGAN, Image-to-Image Translation

In this notebook, we're going to define and train a CycleGAN to read in an image from a set $X$ and transform it so that it looks as if it belongs in set $Y$. Specifically, we'll look at a set of images of Yosemite national park taken either during the summer of winter. The seasons are our two domains!

The objective will be to train generators that learn to transform an image from domain $X$ into an image that looks like it came from domain $Y$ (and vice versa).

Some examples of image data in both sets are pictured below.

Unpaired Training Data

These images do not come with labels, but CycleGANs give us a way to learn the mapping between one image domain and another using an unsupervised approach. A CycleGAN is designed for image-to-image translation and it learns from unpaired training data. This means that in order to train a generator to translate images from domain $X$ to domain $Y$, we do not have to have exact correspondences between individual images in those domains. For example, in the paper that introduced CycleGANs, the authors are able to translate between images of horses and zebras, even though there are no images of a zebra in exactly the same position as a horse or with exactly the same background, etc. Thus, CycleGANs enable learning a mapping from one domain $X$ to another domain $Y$ without having to find perfectly-matched, training pairs!

CycleGAN and Notebook Structure

A CycleGAN is made of two types of networks: discriminators, and generators. In this example, the discriminators are responsible for classifying images as real or fake (for both $X$ and $Y$ kinds of images). The generators are responsible for generating convincing, fake images for both kinds of images.

This notebook will detail the steps you should take to define and train such a CycleGAN.

  1. You'll load in the image data using PyTorch's DataLoader class to efficiently read in images from a specified directory.
  2. Then, you'll be tasked with defining the CycleGAN architecture according to provided specifications. You'll define the discriminator and the generator models.
  3. You'll complete the training cycle by calculating the adversarial and cycle consistency losses for the generator and discriminator network and completing a number of training epochs. It's suggested that you enable GPU usage for training.
  4. Finally, you'll evaluate your model by looking at the loss over time and looking at sample, generated images.

Load and Visualize the Data

We'll first load in and visualize the training data, importing the necessary libraries to do so.

In [11]:
!unzip summer2winter_yosemite.zip # can comment out after executing once
Archive:  summer2winter_yosemite.zip
replace summer2winter_yosemite/.DS_Store? [y]es, [n]o, [A]ll, [N]one, [r]ename: ^C
In [1]:
# loading in and transforming data
import os
import torch
from torch.utils.data import DataLoader
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms

# visualizing data
import matplotlib.pyplot as plt
import numpy as np
import warnings

%matplotlib inline

DataLoaders

The get_data_loader function returns training and test DataLoaders that can load data efficiently and in specified batches. The function has the following parameters:

  • image_type: summer or winter, the names of the directories where the X and Y images are stored
  • image_dir: name of the main image directory, which holds all training and test images
  • image_size: resized, square image dimension (all images will be resized to this dim)
  • batch_size: number of images in one batch of data

The test data is strictly for feeding to our generators, later on, so we can visualize some generated samples on fixed, test data.

You can see that this function is also responsible for making sure our images are of the right, square size (128x128x3) and converted into Tensor image types.

It's suggested that you use the default values of these parameters.

Note: If you are trying this code on a different set of data, you may get better results with larger image_size and batch_size parameters. If you change the batch_size, make sure that you create complete batches in the training loop otherwise you may get an error when trying to save sample data.

In [2]:
def get_data_loader(image_type, image_dir='summer2winter_yosemite', 
                    image_size=128, batch_size=16, num_workers=0):
    """Returns training and test data loaders for a given image type, either 'summer' or 'winter'. 
       These images will be resized to 128x128x3, by default, converted into Tensors, and normalized.
    """
    
    # resize and normalize the images
    transform = transforms.Compose([transforms.Resize(image_size), # resize to 128x128
                                    transforms.ToTensor()])

    # get training and test directories
    image_path = './' + image_dir
    train_path = os.path.join(image_path, image_type)
    test_path = os.path.join(image_path, 'test_{}'.format(image_type))

    # define datasets using ImageFolder
    train_dataset = datasets.ImageFolder(train_path, transform)
    test_dataset = datasets.ImageFolder(test_path, transform)

    # create and return DataLoaders
    train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers)
    test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers)

    return train_loader, test_loader
In [3]:
# Create train and test dataloaders for images from the two domains X and Y
# image_type = directory names for our data
dataloader_X, test_dataloader_X = get_data_loader(image_type='summer')
dataloader_Y, test_dataloader_Y = get_data_loader(image_type='winter')

Display some Training Images

Below we provide a function imshow that reshape some given images and converts them to NumPy images so that they can be displayed by plt. This cell should display a grid that contains a batch of image data from set $X$.

In [4]:
# helper imshow function
def imshow(img):
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    

# get some images from X
dataiter = iter(dataloader_X)
# the "_" is a placeholder for no labels
images, _ = dataiter.next()

# show images
fig = plt.figure(figsize=(12, 8))
imshow(torchvision.utils.make_grid(images))

Next, let's visualize a batch of images from set $Y$.

In [5]:
# get some images from Y
dataiter = iter(dataloader_Y)
images, _ = dataiter.next()

# show images
fig = plt.figure(figsize=(12,8))
imshow(torchvision.utils.make_grid(images))

Pre-processing: scaling from -1 to 1

We need to do a bit of pre-processing; we know that the output of our tanh activated generator will contain pixel values in a range from -1 to 1, and so, we need to rescale our training images to a range of -1 to 1. (Right now, they are in a range from 0-1.)

In [6]:
# current range
img = images[0]

print('Min: ', img.min())
print('Max: ', img.max())
Min:  tensor(1.00000e-03 *
       3.9216)
Max:  tensor(0.9843)
In [7]:
# helper scale function
def scale(x, feature_range=(-1, 1)):
    ''' Scale takes in an image x and returns that image, scaled
       with a feature_range of pixel values from -1 to 1. 
       This function assumes that the input x is already scaled from 0-255.'''
    
    # scale from 0-1 to feature_range
    min, max = feature_range
    x = x * (max - min) + min
    return x
In [8]:
# scaled range
scaled_img = scale(img)

print('Scaled min: ', scaled_img.min())
print('Scaled max: ', scaled_img.max())
Scaled min:  tensor(-0.9922)
Scaled max:  tensor(0.9686)

Define the Model

A CycleGAN is made of two discriminator and two generator networks.

Discriminators

The discriminators, $D_X$ and $D_Y$, in this CycleGAN are convolutional neural networks that see an image and attempt to classify it as real or fake. In this case, real is indicated by an output close to 1 and fake as close to 0. The discriminators have the following architecture:

This network sees a 128x128x3 image, and passes it through 5 convolutional layers that downsample the image by a factor of 2. The first four convolutional layers have a BatchNorm and ReLu activation function applied to their output, and the last acts as a classification layer that outputs one value.

Convolutional Helper Function

To define the discriminators, you're expected to use the provided conv function, which creates a convolutional layer + an optional batch norm layer.

In [9]:
import torch.nn as nn
import torch.nn.functional as F

# helper conv function
def conv(in_channels, out_channels, kernel_size, stride=2, padding=1, batch_norm=True):
    """Creates a convolutional layer, with optional batch normalization.
    """
    layers = []
    conv_layer = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, 
                           kernel_size=kernel_size, stride=stride, padding=padding, bias=False)
    
    layers.append(conv_layer)

    if batch_norm:
        layers.append(nn.BatchNorm2d(out_channels))
    return nn.Sequential(*layers)

Define the Discriminator Architecture

Your task is to fill in the __init__ function with the specified 5 layer conv net architecture. Both $D_X$ and $D_Y$ have the same architecture, so we only need to define one class, and later instantiate two discriminators.

It's recommended that you use a kernel size of 4x4 and use that to determine the correct stride and padding size for each layer. This Stanford resource may also help in determining stride and padding sizes.

  • Define your convolutional layers in __init__
  • Then fill in the forward behavior of the network

The forward function defines how an input image moves through the discriminator, and the most important thing is to pass it through your convolutional layers in order, with a ReLu activation function applied to all but the last layer.

You should not apply a sigmoid activation function to the output, here, and that is because we are planning on using a squared error loss for training. And you can read more about this loss function, later in the notebook.

In [10]:
class Discriminator(nn.Module):
    
    def __init__(self, conv_dim=64):
        super(Discriminator, self).__init__()

        # Define all convolutional layers
        # Should accept an RGB image as input and output a single value
        self.conv1 = conv(3,conv_dim,4,batch_norm=False)
        self.conv2 = conv(conv_dim,conv_dim*2,4)
        self.conv3 = conv(conv_dim*2,conv_dim*4,4)
        self.conv4 = conv(conv_dim*4,conv_dim*8,4)
        #last convolution layer
        self.conv5 = conv(conv_dim*8,1,4,stride=1,batch_norm=False)

    def forward(self, x):
        # define feedforward behavior
        x = F.relu(self.conv1(x))
        x = F.relu(self.conv2(x))
        x = F.relu(self.conv3(x))
        x = F.relu(self.conv4(x))
        x = self.conv5(x)
        
        return x

Generators

The generators, G_XtoY and G_YtoX (sometimes called F), are made of an encoder, a conv net that is responsible for turning an image into a smaller feature representation, and a decoder, a transpose_conv net that is responsible for turning that representation into an transformed image. These generators, one from XtoY and one from YtoX, have the following architecture:

This network sees a 128x128x3 image, compresses it into a feature representation as it goes through three convolutional layers and reaches a series of residual blocks. It goes through a few (typically 6 or more) of these residual blocks, then it goes through three transpose convolutional layers (sometimes called de-conv layers) which upsample the output of the resnet blocks and create a new image!

Note that most of the convolutional and transpose-convolutional layers have BatchNorm and ReLu functions applied to their outputs with the exception of the final transpose convolutional layer, which has a tanh activation function applied to the output. Also, the residual blocks are made of convolutional and batch normalization layers, which we'll go over in more detail, next.


Residual Block Class

To define the generators, you're expected to define a ResidualBlock class which will help you connect the encoder and decoder portions of the generators. You might be wondering, what exactly is a Resnet block? It may sound familiar from something like ResNet50 for image classification, pictured below.

ResNet blocks rely on connecting the output of one layer with the input of an earlier layer. The motivation for this structure is as follows: very deep neural networks can be difficult to train. Deeper networks are more likely to have vanishing or exploding gradients and, therefore, have trouble reaching convergence; batch normalization helps with this a bit. However, during training, we often see that deep networks respond with a kind of training degradation. Essentially, the training accuracy stops improving and gets saturated at some point during training. In the worst cases, deep models would see their training accuracy actually worsen over time!

One solution to this problem is to use Resnet blocks that allow us to learn so-called residual functions as they are applied to layer inputs. You can read more about this proposed architecture in the paper, Deep Residual Learning for Image Recognition by Kaiming He et. al, and the below image is from that paper.

Residual Functions

Usually, when we create a deep learning model, the model (several layers with activations applied) is responsible for learning a mapping, M, from an input x to an output y.

M(x) = y (Equation 1)

Instead of learning a direct mapping from x to y, we can instead define a residual function

F(x) = M(x) - x

This looks at the difference between a mapping applied to x and the original input, x. F(x) is, typically, two convolutional layers + normalization layer and a ReLu in between. These convolutional layers should have the same number of inputs as outputs. This mapping can then be written as the following; a function of the residual function and the input x. The addition step creates a kind of loop that connects the input x to the output, y:

M(x) = F(x) + x (Equation 2) or

y = F(x) + x (Equation 3)

Optimizing a Residual Function

The idea is that it is easier to optimize this residual function F(x) than it is to optimize the original mapping M(x). Consider an example; what if we want y = x?

From our first, direct mapping equation, Equation 1, we could set M(x) = x but it is easier to solve the residual equation F(x) = 0, which, when plugged in to Equation 3, yields y = x.

Defining the ResidualBlock Class

To define the ResidualBlock class, we'll define residual functions (a series of layers), apply them to an input x and add them to that same input. This is defined just like any other neural network, with an __init__ function and the addition step in the forward function.

In our case, you'll want to define the residual block as:

  • Two convolutional layers with the same size input and output
  • Batch normalization applied to the outputs of the convolutional layers
  • A ReLu function on the output of the first convolutional layer

Then, in the forward function, add the input x to this residual block. Feel free to use the helper conv function from above to create this block.

In [11]:
# residual block class
class ResidualBlock(nn.Module):
    """Defines a residual block.
       This adds an input x to a convolutional layer (applied to x) with the same size input and output.
       These blocks allow a model to learn an effective transformation from one domain to another.
    """
    def __init__(self, conv_dim):
        super(ResidualBlock, self).__init__()
        # conv_dim = number of inputs  
        self.conv1 = conv(conv_dim,conv_dim,3,stride=1,padding=1,batch_norm=True)
        self.conv2 = conv(conv_dim,conv_dim,3,stride=1,padding=1,batch_norm=True)
        # define two convolutional layers + batch normalization that will act as our residual function, F(x)
        # layers should have the same shape input as output; I suggest a kernel_size of 3
        
        
    def forward(self, x):
        # apply a ReLu activation the outputs of the first layer
        # return a summed output, x + resnet_block(x)
        out = F.relu(self.conv1(x))
        out1 = x + self.conv2(out)
        
        return x
    

Transpose Convolutional Helper Function

To define the generators, you're expected to use the above conv function, ResidualBlock class, and the below deconv helper function, which creates a transpose convolutional layer + an optional batchnorm layer.

In [12]:
# helper deconv function
def deconv(in_channels, out_channels, kernel_size, stride=2, padding=1, batch_norm=True):
    """Creates a transpose convolutional layer, with optional batch normalization.
    """
    layers = []
    # append transpose conv layer
    layers.append(nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, bias=False))
    # optional batch norm layer
    if batch_norm:
        layers.append(nn.BatchNorm2d(out_channels))
    return nn.Sequential(*layers)

Define the Generator Architecture

  • Complete the __init__ function with the specified 3 layer encoder convolutional net, a series of residual blocks (the number of which is given by n_res_blocks), and then a 3 layer decoder transpose convolutional net.
  • Then complete the forward function to define the forward behavior of the generators. Recall that the last layer has a tanh activation function.

Both $G_{XtoY}$ and $G_{YtoX}$ have the same architecture, so we only need to define one class, and later instantiate two generators.

In [13]:
class CycleGenerator(nn.Module):
    
    def __init__(self, conv_dim=64, n_res_blocks=6):
        super(CycleGenerator, self).__init__()

        # 1. Define the encoder part of the generator
        self.conv1 = conv(3,conv_dim,4)
        self.conv2 = conv(conv_dim,conv_dim*2,4)
        self.conv3 = conv(conv_dim*2,conv_dim*4,4)

        # 2. Define the resnet part of the generator
        resnet = []
        for layer in range(n_res_blocks):
            resnet.append(ResidualBlock(conv_dim*4))
        
        self.res_block = nn.Sequential(*resnet)

        # 3. Define the decoder part of the generator
        self.deconv1 = deconv(conv_dim*4,conv_dim*2,4)
        self.deconv2 = deconv(conv_dim*2,conv_dim,4)
        self.deconv3 = deconv(conv_dim,3,4,batch_norm=False)
        

    def forward(self, x):
        """Given an image x, returns a transformed image."""
        # define feedforward behavior, applying activations as necessary
        x = F.relu(self.conv1(x))
        x = F.relu(self.conv2(x))
        x = F.relu(self.conv3(x))
        
        x = self.res_block(x)
        x = F.relu(self.deconv1(x))
        x = F.relu(self.deconv2(x))
        x = F.tanh(self.deconv3(x))

        return x

Create the complete network

Using the classes you defined earlier, you can define the discriminators and generators necessary to create a complete CycleGAN. The given parameters should work for training.

First, create two discriminators, one for checking if $X$ sample images are real, and one for checking if $Y$ sample images are real. Then the generators. Instantiate two of them, one for transforming a painting into a realistic photo and one for transforming a photo into into a painting.

In [14]:
def create_model(g_conv_dim=64, d_conv_dim=64, n_res_blocks=6):
    """Builds the generators and discriminators."""
    
    # Instantiate generators
    G_XtoY = CycleGenerator(conv_dim=g_conv_dim,n_res_blocks=n_res_blocks)
    G_YtoX = CycleGenerator(conv_dim=g_conv_dim,n_res_blocks=n_res_blocks)
    # Instantiate discriminators
    D_X = Discriminator(conv_dim=d_conv_dim)
    D_Y = Discriminator(conv_dim=d_conv_dim)

    # move models to GPU, if available
    if torch.cuda.is_available():
        device = torch.device("cuda:0")
        G_XtoY.to(device)
        G_YtoX.to(device)
        D_X.to(device)
        D_Y.to(device)
        print('Models moved to GPU.')
    else:
        print('Only CPU available.')

    return G_XtoY, G_YtoX, D_X, D_Y
In [15]:
# call the function to get models
G_XtoY, G_YtoX, D_X, D_Y = create_model()
Models moved to GPU.

Check that you've implemented this correctly

The function create_model should return the two generator and two discriminator networks. After you've defined these discriminator and generator components, it's good practice to check your work. The easiest way to do this is to print out your model architecture and read through it to make sure the parameters are what you expected. The next cell will print out their architectures.

In [16]:
# helper function for printing the model architecture
def print_models(G_XtoY, G_YtoX, D_X, D_Y):
    """Prints model information for the generators and discriminators.
    """
    print("                     G_XtoY                    ")
    print("-----------------------------------------------")
    print(G_XtoY)
    print()

    print("                     G_YtoX                    ")
    print("-----------------------------------------------")
    print(G_YtoX)
    print()

    print("                      D_X                      ")
    print("-----------------------------------------------")
    print(D_X)
    print()

    print("                      D_Y                      ")
    print("-----------------------------------------------")
    print(D_Y)
    print()
    

# print all of the models
print_models(G_XtoY, G_YtoX, D_X, D_Y)
                     G_XtoY                    
-----------------------------------------------
CycleGenerator(
  (conv1): Sequential(
    (0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (conv2): Sequential(
    (0): Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (conv3): Sequential(
    (0): Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (res_block): Sequential(
    (0): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (1): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (2): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (3): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (4): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (5): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
  )
  (deconv1): Sequential(
    (0): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (deconv2): Sequential(
    (0): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (deconv3): Sequential(
    (0): ConvTranspose2d(64, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
  )
)

                     G_YtoX                    
-----------------------------------------------
CycleGenerator(
  (conv1): Sequential(
    (0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (conv2): Sequential(
    (0): Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (conv3): Sequential(
    (0): Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (res_block): Sequential(
    (0): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (1): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (2): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (3): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (4): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
    (5): ResidualBlock(
      (conv1): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
      (conv2): Sequential(
        (0): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      )
    )
  )
  (deconv1): Sequential(
    (0): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (deconv2): Sequential(
    (0): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (deconv3): Sequential(
    (0): ConvTranspose2d(64, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
  )
)

                      D_X                      
-----------------------------------------------
Discriminator(
  (conv1): Sequential(
    (0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
  )
  (conv2): Sequential(
    (0): Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (conv3): Sequential(
    (0): Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (conv4): Sequential(
    (0): Conv2d(256, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (conv5): Sequential(
    (0): Conv2d(512, 1, kernel_size=(4, 4), stride=(1, 1), padding=(1, 1), bias=False)
  )
)

                      D_Y                      
-----------------------------------------------
Discriminator(
  (conv1): Sequential(
    (0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
  )
  (conv2): Sequential(
    (0): Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (conv3): Sequential(
    (0): Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (conv4): Sequential(
    (0): Conv2d(256, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
    (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  )
  (conv5): Sequential(
    (0): Conv2d(512, 1, kernel_size=(4, 4), stride=(1, 1), padding=(1, 1), bias=False)
  )
)

Discriminator and Generator Losses

Computing the discriminator and the generator losses are key to getting a CycleGAN to train.

Image from original paper by Jun-Yan Zhu et. al.

  • The CycleGAN contains two mapping functions $G: X \rightarrow Y$ and $F: Y \rightarrow X$, and associated adversarial discriminators $D_Y$ and $D_X$. (a) $D_Y$ encourages $G$ to translate $X$ into outputs indistinguishable from domain $Y$, and vice versa for $D_X$ and $F$.

  • To further regularize the mappings, we introduce two cycle consistency losses that capture the intuition that if we translate from one domain to the other and back again we should arrive at where we started. (b) Forward cycle-consistency loss and (c) backward cycle-consistency loss.

Least Squares GANs

We've seen that regular GANs treat the discriminator as a classifier with the sigmoid cross entropy loss function. However, this loss function may lead to the vanishing gradients problem during the learning process. To overcome such a problem, we'll use a least squares loss function for the discriminator. This structure is also referred to as a least squares GAN or LSGAN, and you can read the original paper on LSGANs, here. The authors show that LSGANs are able to generate higher quality images than regular GANs and that this loss type is a bit more stable during training!

Discriminator Losses

The discriminator losses will be mean squared errors between the output of the discriminator, given an image, and the target value, 0 or 1, depending on whether it should classify that image as fake or real. For example, for a real image, x, we can train $D_X$ by looking at how close it is to recognizing and image x as real using the mean squared error:

out_x = D_X(x)
real_err = torch.mean((out_x-1)**2)

Generator Losses

Calculating the generator losses will look somewhat similar to calculating the discriminator loss; there will still be steps in which you generate fake images that look like they belong to the set of $X$ images but are based on real images in set $Y$, and vice versa. You'll compute the "real loss" on those generated images by looking at the output of the discriminator as it's applied to these fake images; this time, your generator aims to make the discriminator classify these fake images as real images.

Cycle Consistency Loss

In addition to the adversarial losses, the generator loss terms will also include the cycle consistency loss. This loss is a measure of how good a reconstructed image is, when compared to an original image.

Say you have a fake, generated image, x_hat, and a real image, y. You can get a reconstructed y_hat by applying G_XtoY(x_hat) = y_hat and then check to see if this reconstruction y_hat and the orginal image y match. For this, we recommed calculating the L1 loss, which is an absolute difference, between reconstructed and real images. You may also choose to multiply this loss by some weight value lambda_weight to convey its importance.

The total generator loss will be the sum of the generator losses and the forward and backward cycle consistency losses.


Define Loss Functions

To help us calculate the discriminator and gnerator losses during training, let's define some helpful loss functions. Here, we'll define three.

  1. real_mse_loss that looks at the output of a discriminator and returns the error based on how close that output is to being classified as real. This should be a mean squared error.
  2. fake_mse_loss that looks at the output of a discriminator and returns the error based on how close that output is to being classified as fake. This should be a mean squared error.
  3. cycle_consistency_loss that looks at a set of real image and a set of reconstructed/generated images, and returns the mean absolute error between them. This has a lambda_weight parameter that will weight the mean absolute error in a batch.

It's recommended that you take a look at the original, CycleGAN paper to get a starting value for lambda_weight.

In [33]:
def real_mse_loss(D_out):
    # how close is the produced output from being "real"?
    return torch.mean((D_out-1)**2)

def fake_mse_loss(D_out):
    # how close is the produced output from being "false"?
    return torch.mean(D_out**2)
    

def cycle_consistency_loss(real_im, reconstructed_im, lambda_weight):
    # calculate reconstruction loss 
    reconstr_loss = torch.mean(torch.abs(real_im - reconstructed_im))
    # return weighted loss
    return lambda_weight*reconstr_loss

Define the Optimizers

Next, let's define how this model will update its weights. This, like the GANs you may have seen before, uses Adam optimizers for the discriminator and generator. It's again recommended that you take a look at the original, CycleGAN paper to get starting hyperparameter values.

In [34]:
import torch.optim as optim

# hyperparams for Adam optimizers
lr= 0.0002
beta1= 0.5
beta2= 0.999

g_params = list(G_XtoY.parameters()) + list(G_YtoX.parameters())  # Get generator parameters

# Create optimizers for the generators and discriminators
g_optimizer = optim.Adam(g_params, lr, [beta1, beta2])
d_x_optimizer = optim.Adam(D_X.parameters(), lr, [beta1, beta2])
d_y_optimizer = optim.Adam(D_Y.parameters(), lr, [beta1, beta2])

Training a CycleGAN

When a CycleGAN trains, and sees one batch of real images from set $X$ and $Y$, it trains by performing the following steps:

Training the Discriminators

  1. Compute the discriminator $D_X$ loss on real images
  2. Generate fake images that look like domain $X$ based on real images in domain $Y$
  3. Compute the fake loss for $D_X$
  4. Compute the total loss and perform backpropagation and $D_X$ optimization
  5. Repeat steps 1-4 only with $D_Y$ and your domains switched!

Training the Generators

  1. Generate fake images that look like domain $X$ based on real images in domain $Y$
  2. Compute the generator loss based on how $D_X$ responds to fake $X$
  3. Generate reconstructed $\hat{Y}$ images based on the fake $X$ images generated in step 1
  4. Compute the cycle consistency loss by comparing the reconstructions with real $Y$ images
  5. Repeat steps 1-4 only swapping domains
  6. Add up all the generator and reconstruction losses and perform backpropagation + optimization

Saving Your Progress

A CycleGAN repeats its training process, alternating between training the discriminators and the generators, for a specified number of training iterations. You've been given code that will save some example generated images that the CycleGAN has learned to generate after a certain number of training iterations. Along with looking at the losses, these example generations should give you an idea of how well your network has trained.

Below, you may choose to keep all default parameters; your only task is to calculate the appropriate losses and complete the training cycle.

In [35]:
# import save code
from helpers import save_samples, checkpoint
In [36]:
# train the network
def training_loop(dataloader_X, dataloader_Y, test_dataloader_X, test_dataloader_Y, 
                  n_epochs=2000):
    
    print_every=10
    
    # keep track of losses over time
    losses = []

    test_iter_X = iter(test_dataloader_X)
    test_iter_Y = iter(test_dataloader_Y)

    # Get some fixed data from domains X and Y for sampling. These are images that are held
    # constant throughout training, that allow us to inspect the model's performance.
    fixed_X = test_iter_X.next()[0]
    fixed_Y = test_iter_Y.next()[0]
    fixed_X = scale(fixed_X) # make sure to scale to a range -1 to 1
    fixed_Y = scale(fixed_Y)

    # batches per epoch
    iter_X = iter(dataloader_X)
    iter_Y = iter(dataloader_Y)
    batches_per_epoch = min(len(iter_X), len(iter_Y))

    for epoch in range(1, n_epochs+1):

        # Reset iterators for each epoch
        if epoch % batches_per_epoch == 0:
            iter_X = iter(dataloader_X)
            iter_Y = iter(dataloader_Y)

        images_X, _ = iter_X.next()
        images_X = scale(images_X) # make sure to scale to a range -1 to 1

        images_Y, _ = iter_Y.next()
        images_Y = scale(images_Y)
        
        # move images to GPU if available (otherwise stay on CPU)
        device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
        images_X = images_X.to(device)
        images_Y = images_Y.to(device)


        # ============================================
        #            TRAIN THE DISCRIMINATORS
        # ============================================
        d_x_optimizer.zero_grad()

        ##   First: D_X, real and fake loss components   ##
        out_x = D_X(images_X)

        # 1. Compute the discriminator losses on real images
        D_X_real_loss = real_mse_loss(out_x)
        
        # 2. Generate fake images that look like domain X based on real images in domain Y
        fake_x = G_YtoX(images_Y)

        # 3. Compute the fake loss for D_X
        out_x = D_X(fake_x)
        D_X_fake_loss = fake_mse_loss(out_x)
        
        # 4. Compute the total loss and perform backprop
        d_x_loss = D_X_real_loss+D_X_fake_loss
        d_x_loss.backward()
        d_x_optimizer.step()

        
        ##   Second: D_Y, real and fake loss components   ##
        d_y_optimizer.zero_grad()
        out_y = D_Y(images_Y)
        D_Y_real_loss = real_mse_loss(out_y)
        fake_y = G_XtoY(images_X)
        out_y = D_Y(fake_y)
        D_Y_fake_loss = fake_mse_loss(out_y)
        d_y_loss = D_Y_real_loss + D_Y_fake_loss
        d_y_loss.backward()
        d_y_optimizer.step()
        


        # =========================================
        #            TRAIN THE GENERATORS
        # =========================================
        g_optimizer.zero_grad()

        ##    First: generate fake X images and reconstructed Y images  ##
        fake_x = G_YtoX(images_Y)

        # 1. Generate fake images that look like domain X based on real images in domain Y
        out_x = D_X(fake_x)
        g_YtoX_loss = real_mse_loss(out_x)

        # 2. Compute the generator loss based on domain X

        # 3. Create a reconstructed y
        
        # 4. Compute the cycle consistency loss (the reconstruction loss)
        reconstructed_y = G_XtoY(fake_x)
        reconstructed_y_loss = cycle_consistency_loss(images_Y, reconstructed_y, lambda_weight=10)

        ##    Second: generate fake Y images and reconstructed X images    ##
        fake_y = G_XtoY(images_X)
        out_y = D_Y(fake_y)
        g_XtoY_loss = real_mse_loss(out_y)
        reconstructed_x = G_YtoX(fake_y)
        reconstructed_x_loss = cycle_consistency_loss(images_X, reconstructed_x, lambda_weight=10)
        # 5. Add up all generator and reconstructed losses and perform backprop
        g_total_loss = g_YtoX_loss + g_XtoY_loss + reconstructed_y_loss + reconstructed_x_loss
        g_total_loss.backward()
        g_optimizer.step()

        
        # Print the log info
        if epoch % print_every == 0:
            # append real and fake discriminator losses and the generator loss
            losses.append((d_x_loss.item(), d_y_loss.item(), g_total_loss.item()))
            print('Epoch [{:5d}/{:5d}] | d_X_loss: {:6.4f} | d_Y_loss: {:6.4f} | g_total_loss: {:6.4f}'.format(
                    epoch, n_epochs, d_x_loss.item(), d_y_loss.item(), g_total_loss.item()))

            
        sample_every=100
        # Save the generated samples
        if epoch % sample_every == 0:
            G_YtoX.eval() # set generators to eval mode for sample generation
            G_XtoY.eval()
            save_samples(epoch, fixed_Y, fixed_X, G_YtoX, G_XtoY, batch_size=16)
            G_YtoX.train()
            G_XtoY.train()

        # uncomment these lines, if you want to save your model
#         checkpoint_every=1000
#         # Save the model parameters
#         if epoch % checkpoint_every == 0:
#             checkpoint(epoch, G_XtoY, G_YtoX, D_X, D_Y)

    return losses
In [37]:
n_epochs = 2000 # keep this small when testing if a model first works, then increase it to >=1000

losses = training_loop(dataloader_X, dataloader_Y, test_dataloader_X, test_dataloader_Y, n_epochs=n_epochs)
Epoch [   10/ 2000] | d_X_loss: 0.0024 | d_Y_loss: 0.0886 | g_total_loss: 14.8454
Epoch [   20/ 2000] | d_X_loss: 0.0016 | d_Y_loss: 0.0155 | g_total_loss: 9.9181
Epoch [   30/ 2000] | d_X_loss: 0.0047 | d_Y_loss: 0.0513 | g_total_loss: 9.5976
Epoch [   40/ 2000] | d_X_loss: 0.0042 | d_Y_loss: 0.0460 | g_total_loss: 8.5036
Epoch [   50/ 2000] | d_X_loss: 0.0015 | d_Y_loss: 0.1004 | g_total_loss: 8.8259
Epoch [   60/ 2000] | d_X_loss: 0.0085 | d_Y_loss: 0.0361 | g_total_loss: 8.3962
Epoch [   70/ 2000] | d_X_loss: 0.0025 | d_Y_loss: 0.5471 | g_total_loss: 7.8665
Epoch [   80/ 2000] | d_X_loss: 0.0054 | d_Y_loss: 0.0495 | g_total_loss: 8.1460
Epoch [   90/ 2000] | d_X_loss: 0.0063 | d_Y_loss: 0.0527 | g_total_loss: 7.6180
Epoch [  100/ 2000] | d_X_loss: 0.0027 | d_Y_loss: 0.2045 | g_total_loss: 7.9189
Saved samples_cyclegan/sample-000100-X-Y.png
Saved samples_cyclegan/sample-000100-Y-X.png
Epoch [  110/ 2000] | d_X_loss: 0.0069 | d_Y_loss: 0.0925 | g_total_loss: 7.9602
Epoch [  120/ 2000] | d_X_loss: 0.0018 | d_Y_loss: 0.3930 | g_total_loss: 8.1447
Epoch [  130/ 2000] | d_X_loss: 0.0071 | d_Y_loss: 0.1265 | g_total_loss: 7.6541
Epoch [  140/ 2000] | d_X_loss: 0.0012 | d_Y_loss: 0.0811 | g_total_loss: 8.0854
Epoch [  150/ 2000] | d_X_loss: 0.0023 | d_Y_loss: 0.1368 | g_total_loss: 7.2610
Epoch [  160/ 2000] | d_X_loss: 0.0017 | d_Y_loss: 0.2346 | g_total_loss: 7.8361
Epoch [  170/ 2000] | d_X_loss: 0.0008 | d_Y_loss: 0.1954 | g_total_loss: 7.9425
Epoch [  180/ 2000] | d_X_loss: 0.0039 | d_Y_loss: 0.4411 | g_total_loss: 8.3118
Epoch [  190/ 2000] | d_X_loss: 0.0018 | d_Y_loss: 0.1966 | g_total_loss: 8.0450
Epoch [  200/ 2000] | d_X_loss: 0.0011 | d_Y_loss: 0.1182 | g_total_loss: 7.7491
Saved samples_cyclegan/sample-000200-X-Y.png
Saved samples_cyclegan/sample-000200-Y-X.png
Epoch [  210/ 2000] | d_X_loss: 0.0005 | d_Y_loss: 0.1096 | g_total_loss: 7.9450
Epoch [  220/ 2000] | d_X_loss: 0.0010 | d_Y_loss: 0.2052 | g_total_loss: 7.1727
Epoch [  230/ 2000] | d_X_loss: 0.0014 | d_Y_loss: 0.6334 | g_total_loss: 7.2541
Epoch [  240/ 2000] | d_X_loss: 0.0033 | d_Y_loss: 0.1558 | g_total_loss: 7.8138
Epoch [  250/ 2000] | d_X_loss: 0.5725 | d_Y_loss: 0.4542 | g_total_loss: 9.0760
Epoch [  260/ 2000] | d_X_loss: 0.0066 | d_Y_loss: 0.4232 | g_total_loss: 7.4804
Epoch [  270/ 2000] | d_X_loss: 0.0021 | d_Y_loss: 0.4282 | g_total_loss: 6.9116
Epoch [  280/ 2000] | d_X_loss: 0.0033 | d_Y_loss: 0.0733 | g_total_loss: 8.0826
Epoch [  290/ 2000] | d_X_loss: 0.0020 | d_Y_loss: 0.3569 | g_total_loss: 7.4678
Epoch [  300/ 2000] | d_X_loss: 0.0019 | d_Y_loss: 0.5074 | g_total_loss: 7.7448
Saved samples_cyclegan/sample-000300-X-Y.png
Saved samples_cyclegan/sample-000300-Y-X.png
Epoch [  310/ 2000] | d_X_loss: 0.0015 | d_Y_loss: 0.4017 | g_total_loss: 6.9745
Epoch [  320/ 2000] | d_X_loss: 0.0010 | d_Y_loss: 0.3371 | g_total_loss: 7.7715
Epoch [  330/ 2000] | d_X_loss: 0.0020 | d_Y_loss: 0.4018 | g_total_loss: 6.9008
Epoch [  340/ 2000] | d_X_loss: 0.0027 | d_Y_loss: 0.5049 | g_total_loss: 7.5718
Epoch [  350/ 2000] | d_X_loss: 0.0014 | d_Y_loss: 0.4006 | g_total_loss: 7.3538
Epoch [  360/ 2000] | d_X_loss: 0.0015 | d_Y_loss: 0.3450 | g_total_loss: 6.3787
Epoch [  370/ 2000] | d_X_loss: 0.0006 | d_Y_loss: 0.5596 | g_total_loss: 7.5518
Epoch [  380/ 2000] | d_X_loss: 0.0027 | d_Y_loss: 0.3142 | g_total_loss: 6.6822
Epoch [  390/ 2000] | d_X_loss: 0.0013 | d_Y_loss: 0.3103 | g_total_loss: 7.1382
Epoch [  400/ 2000] | d_X_loss: 0.0013 | d_Y_loss: 0.5153 | g_total_loss: 7.2498
Saved samples_cyclegan/sample-000400-X-Y.png
Saved samples_cyclegan/sample-000400-Y-X.png
Epoch [  410/ 2000] | d_X_loss: 0.0028 | d_Y_loss: 0.3603 | g_total_loss: 7.3518
Epoch [  420/ 2000] | d_X_loss: 0.0037 | d_Y_loss: 0.5370 | g_total_loss: 6.7488
Epoch [  430/ 2000] | d_X_loss: 0.0013 | d_Y_loss: 0.4176 | g_total_loss: 7.0595
Epoch [  440/ 2000] | d_X_loss: 0.0025 | d_Y_loss: 0.5466 | g_total_loss: 6.4315
Epoch [  450/ 2000] | d_X_loss: 0.0021 | d_Y_loss: 0.4313 | g_total_loss: 6.6249
Epoch [  460/ 2000] | d_X_loss: 0.0030 | d_Y_loss: 0.4514 | g_total_loss: 6.0826
Epoch [  470/ 2000] | d_X_loss: 0.0011 | d_Y_loss: 0.4468 | g_total_loss: 6.2829
Epoch [  480/ 2000] | d_X_loss: 0.0014 | d_Y_loss: 0.4580 | g_total_loss: 6.2928
Epoch [  490/ 2000] | d_X_loss: 0.0024 | d_Y_loss: 0.3934 | g_total_loss: 6.8623
Epoch [  500/ 2000] | d_X_loss: 0.0013 | d_Y_loss: 0.5192 | g_total_loss: 6.2106
Saved samples_cyclegan/sample-000500-X-Y.png
Saved samples_cyclegan/sample-000500-Y-X.png
Epoch [  510/ 2000] | d_X_loss: 0.0028 | d_Y_loss: 0.3800 | g_total_loss: 6.3854
Epoch [  520/ 2000] | d_X_loss: 0.0020 | d_Y_loss: 0.4691 | g_total_loss: 6.7327
Epoch [  530/ 2000] | d_X_loss: 0.0017 | d_Y_loss: 0.3380 | g_total_loss: 6.4196
Epoch [  540/ 2000] | d_X_loss: 0.0025 | d_Y_loss: 0.5079 | g_total_loss: 5.7040
Epoch [  550/ 2000] | d_X_loss: 0.0056 | d_Y_loss: 0.4429 | g_total_loss: 5.9325
Epoch [  560/ 2000] | d_X_loss: 0.0012 | d_Y_loss: 0.4636 | g_total_loss: 5.8983
Epoch [  570/ 2000] | d_X_loss: 0.0021 | d_Y_loss: 0.4735 | g_total_loss: 5.8253
Epoch [  580/ 2000] | d_X_loss: 0.0033 | d_Y_loss: 0.3989 | g_total_loss: 5.7056
Epoch [  590/ 2000] | d_X_loss: 0.0018 | d_Y_loss: 0.4887 | g_total_loss: 5.5597
Epoch [  600/ 2000] | d_X_loss: 0.0029 | d_Y_loss: 0.4691 | g_total_loss: 6.2425
Saved samples_cyclegan/sample-000600-X-Y.png
Saved samples_cyclegan/sample-000600-Y-X.png
Epoch [  610/ 2000] | d_X_loss: 0.0010 | d_Y_loss: 0.6311 | g_total_loss: 5.3977
Epoch [  620/ 2000] | d_X_loss: 0.0016 | d_Y_loss: 0.4430 | g_total_loss: 5.6093
Epoch [  630/ 2000] | d_X_loss: 0.0006 | d_Y_loss: 0.5022 | g_total_loss: 5.5284
Epoch [  640/ 2000] | d_X_loss: 0.0019 | d_Y_loss: 0.3954 | g_total_loss: 5.5117
Epoch [  650/ 2000] | d_X_loss: 0.0027 | d_Y_loss: 0.3850 | g_total_loss: 5.0045
Epoch [  660/ 2000] | d_X_loss: 0.0450 | d_Y_loss: 0.5034 | g_total_loss: 4.5842
Epoch [  670/ 2000] | d_X_loss: 0.0629 | d_Y_loss: 0.2930 | g_total_loss: 5.9072
Epoch [  680/ 2000] | d_X_loss: 0.4414 | d_Y_loss: 0.3138 | g_total_loss: 5.6856
Epoch [  690/ 2000] | d_X_loss: 0.1216 | d_Y_loss: 0.4919 | g_total_loss: 4.7893
Epoch [  700/ 2000] | d_X_loss: 0.6416 | d_Y_loss: 0.4753 | g_total_loss: 4.0841
Saved samples_cyclegan/sample-000700-X-Y.png
Saved samples_cyclegan/sample-000700-Y-X.png
Epoch [  710/ 2000] | d_X_loss: 0.1359 | d_Y_loss: 0.4224 | g_total_loss: 4.8167
Epoch [  720/ 2000] | d_X_loss: 0.9396 | d_Y_loss: 0.3483 | g_total_loss: 4.7620
Epoch [  730/ 2000] | d_X_loss: 0.7786 | d_Y_loss: 0.3245 | g_total_loss: 3.7146
Epoch [  740/ 2000] | d_X_loss: 0.6896 | d_Y_loss: 0.4382 | g_total_loss: 3.8817
Epoch [  750/ 2000] | d_X_loss: 0.5258 | d_Y_loss: 0.3742 | g_total_loss: 3.8007
Epoch [  760/ 2000] | d_X_loss: 0.4430 | d_Y_loss: 0.4359 | g_total_loss: 3.4658
Epoch [  770/ 2000] | d_X_loss: 0.5017 | d_Y_loss: 0.3436 | g_total_loss: 3.3791
Epoch [  780/ 2000] | d_X_loss: 0.4186 | d_Y_loss: 0.4989 | g_total_loss: 3.5405
Epoch [  790/ 2000] | d_X_loss: 0.4773 | d_Y_loss: 0.5884 | g_total_loss: 3.6358
Epoch [  800/ 2000] | d_X_loss: 0.4571 | d_Y_loss: 0.2722 | g_total_loss: 3.4248
Saved samples_cyclegan/sample-000800-X-Y.png
Saved samples_cyclegan/sample-000800-Y-X.png
Epoch [  810/ 2000] | d_X_loss: 0.4552 | d_Y_loss: 0.4013 | g_total_loss: 3.3011
Epoch [  820/ 2000] | d_X_loss: 0.4634 | d_Y_loss: 0.3061 | g_total_loss: 3.5831
Epoch [  830/ 2000] | d_X_loss: 0.5289 | d_Y_loss: 0.5658 | g_total_loss: 3.5354
Epoch [  840/ 2000] | d_X_loss: 0.4544 | d_Y_loss: 0.5136 | g_total_loss: 3.6392
Epoch [  850/ 2000] | d_X_loss: 0.3716 | d_Y_loss: 0.4585 | g_total_loss: 3.5294
Epoch [  860/ 2000] | d_X_loss: 0.3333 | d_Y_loss: 0.4016 | g_total_loss: 3.6494
Epoch [  870/ 2000] | d_X_loss: 0.3417 | d_Y_loss: 0.3940 | g_total_loss: 3.4658
Epoch [  880/ 2000] | d_X_loss: 0.4148 | d_Y_loss: 0.3466 | g_total_loss: 3.7912
Epoch [  890/ 2000] | d_X_loss: 0.4457 | d_Y_loss: 0.5745 | g_total_loss: 3.4518
Epoch [  900/ 2000] | d_X_loss: 0.4380 | d_Y_loss: 0.5064 | g_total_loss: 3.4695
Saved samples_cyclegan/sample-000900-X-Y.png
Saved samples_cyclegan/sample-000900-Y-X.png
Epoch [  910/ 2000] | d_X_loss: 0.3999 | d_Y_loss: 0.3781 | g_total_loss: 3.5082
Epoch [  920/ 2000] | d_X_loss: 0.3483 | d_Y_loss: 0.4749 | g_total_loss: 3.6144
Epoch [  930/ 2000] | d_X_loss: 0.5099 | d_Y_loss: 0.6220 | g_total_loss: 3.6494
Epoch [  940/ 2000] | d_X_loss: 0.3255 | d_Y_loss: 0.3167 | g_total_loss: 3.6887
Epoch [  950/ 2000] | d_X_loss: 0.4808 | d_Y_loss: 0.5008 | g_total_loss: 3.0340
Epoch [  960/ 2000] | d_X_loss: 0.4016 | d_Y_loss: 0.5166 | g_total_loss: 2.9327
Epoch [  970/ 2000] | d_X_loss: 0.6588 | d_Y_loss: 0.3523 | g_total_loss: 3.9842
Epoch [  980/ 2000] | d_X_loss: 0.3477 | d_Y_loss: 0.5961 | g_total_loss: 3.1965
Epoch [  990/ 2000] | d_X_loss: 0.5485 | d_Y_loss: 0.3536 | g_total_loss: 4.1773
Epoch [ 1000/ 2000] | d_X_loss: 0.4054 | d_Y_loss: 0.5583 | g_total_loss: 3.1592
Saved samples_cyclegan/sample-001000-X-Y.png
Saved samples_cyclegan/sample-001000-Y-X.png
Epoch [ 1010/ 2000] | d_X_loss: 0.3924 | d_Y_loss: 0.4363 | g_total_loss: 3.7672
Epoch [ 1020/ 2000] | d_X_loss: 0.3022 | d_Y_loss: 0.3175 | g_total_loss: 3.6321
Epoch [ 1030/ 2000] | d_X_loss: 0.6995 | d_Y_loss: 0.4706 | g_total_loss: 3.6091
Epoch [ 1040/ 2000] | d_X_loss: 0.4856 | d_Y_loss: 0.3616 | g_total_loss: 2.9656
Epoch [ 1050/ 2000] | d_X_loss: 0.4289 | d_Y_loss: 0.3703 | g_total_loss: 3.3788
Epoch [ 1060/ 2000] | d_X_loss: 0.4052 | d_Y_loss: 0.4266 | g_total_loss: 3.5005
Epoch [ 1070/ 2000] | d_X_loss: 0.3247 | d_Y_loss: 0.3546 | g_total_loss: 2.9919
Epoch [ 1080/ 2000] | d_X_loss: 0.3332 | d_Y_loss: 0.3965 | g_total_loss: 3.6186
Epoch [ 1090/ 2000] | d_X_loss: 0.3979 | d_Y_loss: 0.3940 | g_total_loss: 3.9921
Epoch [ 1100/ 2000] | d_X_loss: 0.3692 | d_Y_loss: 0.4453 | g_total_loss: 3.6058
Saved samples_cyclegan/sample-001100-X-Y.png
Saved samples_cyclegan/sample-001100-Y-X.png
Epoch [ 1110/ 2000] | d_X_loss: 0.5940 | d_Y_loss: 0.5842 | g_total_loss: 3.1245
Epoch [ 1120/ 2000] | d_X_loss: 0.3751 | d_Y_loss: 0.2828 | g_total_loss: 3.6297
Epoch [ 1130/ 2000] | d_X_loss: 0.4107 | d_Y_loss: 0.3970 | g_total_loss: 3.5986
Epoch [ 1140/ 2000] | d_X_loss: 0.3675 | d_Y_loss: 0.3452 | g_total_loss: 3.2958
Epoch [ 1150/ 2000] | d_X_loss: 0.3065 | d_Y_loss: 0.2857 | g_total_loss: 3.5805
Epoch [ 1160/ 2000] | d_X_loss: 0.4544 | d_Y_loss: 0.7020 | g_total_loss: 3.1385
Epoch [ 1170/ 2000] | d_X_loss: 0.3019 | d_Y_loss: 0.3063 | g_total_loss: 3.3463
Epoch [ 1180/ 2000] | d_X_loss: 0.3025 | d_Y_loss: 0.3721 | g_total_loss: 3.4073
Epoch [ 1190/ 2000] | d_X_loss: 0.4422 | d_Y_loss: 0.3173 | g_total_loss: 3.4473
Epoch [ 1200/ 2000] | d_X_loss: 0.3899 | d_Y_loss: 0.4456 | g_total_loss: 3.3605
Saved samples_cyclegan/sample-001200-X-Y.png
Saved samples_cyclegan/sample-001200-Y-X.png
Epoch [ 1210/ 2000] | d_X_loss: 0.3332 | d_Y_loss: 0.3955 | g_total_loss: 3.5283
Epoch [ 1220/ 2000] | d_X_loss: 0.4541 | d_Y_loss: 0.5475 | g_total_loss: 3.2465
Epoch [ 1230/ 2000] | d_X_loss: 0.2992 | d_Y_loss: 0.3309 | g_total_loss: 3.9508
Epoch [ 1240/ 2000] | d_X_loss: 0.5286 | d_Y_loss: 0.6192 | g_total_loss: 3.1153
Epoch [ 1250/ 2000] | d_X_loss: 0.4067 | d_Y_loss: 0.3038 | g_total_loss: 3.3722
Epoch [ 1260/ 2000] | d_X_loss: 0.3729 | d_Y_loss: 0.3640 | g_total_loss: 3.2266
Epoch [ 1270/ 2000] | d_X_loss: 0.3151 | d_Y_loss: 0.2443 | g_total_loss: 3.6774
Epoch [ 1280/ 2000] | d_X_loss: 0.3113 | d_Y_loss: 0.3795 | g_total_loss: 3.8635
Epoch [ 1290/ 2000] | d_X_loss: 0.4041 | d_Y_loss: 0.3571 | g_total_loss: 3.1535
Epoch [ 1300/ 2000] | d_X_loss: 0.3493 | d_Y_loss: 0.2408 | g_total_loss: 3.3592
Saved samples_cyclegan/sample-001300-X-Y.png
Saved samples_cyclegan/sample-001300-Y-X.png
Epoch [ 1310/ 2000] | d_X_loss: 0.4651 | d_Y_loss: 0.4895 | g_total_loss: 3.2216
Epoch [ 1320/ 2000] | d_X_loss: 0.3595 | d_Y_loss: 0.3876 | g_total_loss: 3.3542
Epoch [ 1330/ 2000] | d_X_loss: 0.3113 | d_Y_loss: 0.3688 | g_total_loss: 3.4687
Epoch [ 1340/ 2000] | d_X_loss: 0.5832 | d_Y_loss: 0.6363 | g_total_loss: 2.9622
Epoch [ 1350/ 2000] | d_X_loss: 0.4813 | d_Y_loss: 0.3949 | g_total_loss: 3.6287
Epoch [ 1360/ 2000] | d_X_loss: 0.3248 | d_Y_loss: 0.3575 | g_total_loss: 3.6318
Epoch [ 1370/ 2000] | d_X_loss: 0.2691 | d_Y_loss: 0.3148 | g_total_loss: 3.1423
Epoch [ 1380/ 2000] | d_X_loss: 0.4071 | d_Y_loss: 0.2738 | g_total_loss: 3.3088
Epoch [ 1390/ 2000] | d_X_loss: 0.4361 | d_Y_loss: 0.3429 | g_total_loss: 3.4841
Epoch [ 1400/ 2000] | d_X_loss: 0.3460 | d_Y_loss: 0.3784 | g_total_loss: 3.1944
Saved samples_cyclegan/sample-001400-X-Y.png
Saved samples_cyclegan/sample-001400-Y-X.png
Epoch [ 1410/ 2000] | d_X_loss: 0.2144 | d_Y_loss: 0.2335 | g_total_loss: 4.0139
Epoch [ 1420/ 2000] | d_X_loss: 0.4622 | d_Y_loss: 0.2617 | g_total_loss: 3.2523
Epoch [ 1430/ 2000] | d_X_loss: 0.4835 | d_Y_loss: 0.5969 | g_total_loss: 3.1037
Epoch [ 1440/ 2000] | d_X_loss: 0.4486 | d_Y_loss: 0.5410 | g_total_loss: 3.3596
Epoch [ 1450/ 2000] | d_X_loss: 0.3136 | d_Y_loss: 0.2316 | g_total_loss: 3.1009
Epoch [ 1460/ 2000] | d_X_loss: 0.3442 | d_Y_loss: 0.2543 | g_total_loss: 3.8523
Epoch [ 1470/ 2000] | d_X_loss: 0.4772 | d_Y_loss: 0.3462 | g_total_loss: 3.5519
Epoch [ 1480/ 2000] | d_X_loss: 0.3421 | d_Y_loss: 0.2799 | g_total_loss: 3.3915
Epoch [ 1490/ 2000] | d_X_loss: 0.3045 | d_Y_loss: 0.3422 | g_total_loss: 3.6934
Epoch [ 1500/ 2000] | d_X_loss: 0.1938 | d_Y_loss: 0.1209 | g_total_loss: 3.6349
Saved samples_cyclegan/sample-001500-X-Y.png
Saved samples_cyclegan/sample-001500-Y-X.png
Epoch [ 1510/ 2000] | d_X_loss: 0.3892 | d_Y_loss: 0.4114 | g_total_loss: 3.1401
Epoch [ 1520/ 2000] | d_X_loss: 0.4314 | d_Y_loss: 0.4822 | g_total_loss: 3.0313
Epoch [ 1530/ 2000] | d_X_loss: 0.4122 | d_Y_loss: 0.4786 | g_total_loss: 3.5027
Epoch [ 1540/ 2000] | d_X_loss: 0.6344 | d_Y_loss: 0.5812 | g_total_loss: 3.0080
Epoch [ 1550/ 2000] | d_X_loss: 0.2879 | d_Y_loss: 0.2551 | g_total_loss: 3.5498
Epoch [ 1560/ 2000] | d_X_loss: 0.3898 | d_Y_loss: 0.2919 | g_total_loss: 3.6373
Epoch [ 1570/ 2000] | d_X_loss: 0.1682 | d_Y_loss: 0.2850 | g_total_loss: 3.7280
Epoch [ 1580/ 2000] | d_X_loss: 0.4443 | d_Y_loss: 0.5029 | g_total_loss: 3.1554
Epoch [ 1590/ 2000] | d_X_loss: 0.4895 | d_Y_loss: 0.5133 | g_total_loss: 3.0964
Epoch [ 1600/ 2000] | d_X_loss: 0.2641 | d_Y_loss: 0.2580 | g_total_loss: 3.8484
Saved samples_cyclegan/sample-001600-X-Y.png
Saved samples_cyclegan/sample-001600-Y-X.png
Epoch [ 1610/ 2000] | d_X_loss: 0.3638 | d_Y_loss: 0.4803 | g_total_loss: 3.3064
Epoch [ 1620/ 2000] | d_X_loss: 0.2007 | d_Y_loss: 0.2179 | g_total_loss: 3.4011
Epoch [ 1630/ 2000] | d_X_loss: 0.4168 | d_Y_loss: 0.3814 | g_total_loss: 3.0289
Epoch [ 1640/ 2000] | d_X_loss: 0.3591 | d_Y_loss: 0.3165 | g_total_loss: 3.5742
Epoch [ 1650/ 2000] | d_X_loss: 0.3273 | d_Y_loss: 0.3401 | g_total_loss: 3.1264
Epoch [ 1660/ 2000] | d_X_loss: 0.4061 | d_Y_loss: 0.3456 | g_total_loss: 3.2260
Epoch [ 1670/ 2000] | d_X_loss: 0.4423 | d_Y_loss: 0.3325 | g_total_loss: 3.1169
Epoch [ 1680/ 2000] | d_X_loss: 0.2574 | d_Y_loss: 0.2422 | g_total_loss: 3.6437
Epoch [ 1690/ 2000] | d_X_loss: 0.4648 | d_Y_loss: 0.3337 | g_total_loss: 3.3901
Epoch [ 1700/ 2000] | d_X_loss: 0.3777 | d_Y_loss: 0.5073 | g_total_loss: 3.0174
Saved samples_cyclegan/sample-001700-X-Y.png
Saved samples_cyclegan/sample-001700-Y-X.png
Epoch [ 1710/ 2000] | d_X_loss: 0.2363 | d_Y_loss: 0.3244 | g_total_loss: 3.6352
Epoch [ 1720/ 2000] | d_X_loss: 0.4532 | d_Y_loss: 0.4117 | g_total_loss: 2.7635
Epoch [ 1730/ 2000] | d_X_loss: 0.3057 | d_Y_loss: 0.1544 | g_total_loss: 3.7845
Epoch [ 1740/ 2000] | d_X_loss: 0.4912 | d_Y_loss: 0.5646 | g_total_loss: 2.9145
Epoch [ 1750/ 2000] | d_X_loss: 0.2746 | d_Y_loss: 0.2514 | g_total_loss: 3.6094
Epoch [ 1760/ 2000] | d_X_loss: 0.5900 | d_Y_loss: 0.5618 | g_total_loss: 3.4004
Epoch [ 1770/ 2000] | d_X_loss: 0.2563 | d_Y_loss: 0.2636 | g_total_loss: 3.7819
Epoch [ 1780/ 2000] | d_X_loss: 0.2501 | d_Y_loss: 0.2628 | g_total_loss: 3.2646
Epoch [ 1790/ 2000] | d_X_loss: 0.4277 | d_Y_loss: 0.5180 | g_total_loss: 3.8095
Epoch [ 1800/ 2000] | d_X_loss: 0.4272 | d_Y_loss: 0.2705 | g_total_loss: 3.2265
Saved samples_cyclegan/sample-001800-X-Y.png
Saved samples_cyclegan/sample-001800-Y-X.png
Epoch [ 1810/ 2000] | d_X_loss: 0.5145 | d_Y_loss: 0.3723 | g_total_loss: 3.1106
Epoch [ 1820/ 2000] | d_X_loss: 0.4698 | d_Y_loss: 0.3909 | g_total_loss: 3.3165
Epoch [ 1830/ 2000] | d_X_loss: 0.3009 | d_Y_loss: 0.3282 | g_total_loss: 3.3987
Epoch [ 1840/ 2000] | d_X_loss: 0.3299 | d_Y_loss: 0.3333 | g_total_loss: 3.5426
Epoch [ 1850/ 2000] | d_X_loss: 0.4157 | d_Y_loss: 0.3283 | g_total_loss: 3.6108
Epoch [ 1860/ 2000] | d_X_loss: 0.4317 | d_Y_loss: 0.2773 | g_total_loss: 4.0293
Epoch [ 1870/ 2000] | d_X_loss: 0.3386 | d_Y_loss: 0.2616 | g_total_loss: 3.2619
Epoch [ 1880/ 2000] | d_X_loss: 0.3112 | d_Y_loss: 0.3946 | g_total_loss: 3.4613
Epoch [ 1890/ 2000] | d_X_loss: 0.6003 | d_Y_loss: 0.7211 | g_total_loss: 3.6908
Epoch [ 1900/ 2000] | d_X_loss: 0.3752 | d_Y_loss: 0.3993 | g_total_loss: 3.6322
Saved samples_cyclegan/sample-001900-X-Y.png
Saved samples_cyclegan/sample-001900-Y-X.png
Epoch [ 1910/ 2000] | d_X_loss: 0.2282 | d_Y_loss: 0.2306 | g_total_loss: 3.3178
Epoch [ 1920/ 2000] | d_X_loss: 0.4885 | d_Y_loss: 0.4358 | g_total_loss: 3.2147
Epoch [ 1930/ 2000] | d_X_loss: 0.2112 | d_Y_loss: 0.3398 | g_total_loss: 3.6879
Epoch [ 1940/ 2000] | d_X_loss: 0.3880 | d_Y_loss: 0.3620 | g_total_loss: 3.0579
Epoch [ 1950/ 2000] | d_X_loss: 0.4307 | d_Y_loss: 0.2102 | g_total_loss: 3.6428
Epoch [ 1960/ 2000] | d_X_loss: 0.2814 | d_Y_loss: 0.3520 | g_total_loss: 3.3563
Epoch [ 1970/ 2000] | d_X_loss: 0.3022 | d_Y_loss: 0.3145 | g_total_loss: 3.4251
Epoch [ 1980/ 2000] | d_X_loss: 0.3600 | d_Y_loss: 0.2850 | g_total_loss: 3.5404
Epoch [ 1990/ 2000] | d_X_loss: 0.2804 | d_Y_loss: 0.2703 | g_total_loss: 4.0097
Epoch [ 2000/ 2000] | d_X_loss: 0.3430 | d_Y_loss: 0.3491 | g_total_loss: 3.2620
Saved samples_cyclegan/sample-002000-X-Y.png
Saved samples_cyclegan/sample-002000-Y-X.png
In [ ]:
 

Tips on Training and Loss Patterns

A lot of experimentation goes into finding the best hyperparameters such that the generators and discriminators don't overpower each other. It's often a good starting point to look at existing papers to find what has worked in previous experiments, I'd recommend this DCGAN paper in addition to the original CycleGAN paper to see what worked for them. Then, you can try your own experiments based off of a good foundation.

Discriminator Losses

When you display the generator and discriminator losses you should see that there is always some discriminator loss; recall that we are trying to design a model that can generate good "fake" images. So, the ideal discriminator will not be able to tell the difference between real and fake images and, as such, will always have some loss. You should also see that $D_X$ and $D_Y$ are roughly at the same loss levels; if they are not, this indicates that your training is favoring one type of discriminator over the other and you may need to look at biases in your models or data.

Generator Loss

The generator's loss should start significantly higher than the discriminator losses because it is accounting for the loss of both generators and weighted reconstruction errors. You should see this loss decrease a lot at the start of training because initial, generated images are often far-off from being good fakes. After some time it may level off; this is normal since the generator and discriminator are both improving as they train. If you see that the loss is jumping around a lot, over time, you may want to try decreasing your learning rates or changing your cycle consistency loss to be a little more/less weighted.

In [38]:
fig, ax = plt.subplots(figsize=(12,8))
losses = np.array(losses)
plt.plot(losses.T[0], label='Discriminator, X', alpha=0.5)
plt.plot(losses.T[1], label='Discriminator, Y', alpha=0.5)
plt.plot(losses.T[2], label='Generators', alpha=0.5)
plt.title("Training Losses")
plt.legend()
Out[38]:
<matplotlib.legend.Legend at 0x7f2150cd5550>

Evaluate the Result!

As you trained this model, you may have chosen to sample and save the results of your generated images after a certain number of training iterations. This gives you a way to see whether or not your Generators are creating good fake images. For example, the image below depicts real images in the $Y$ set, and the corresponding generated images during different points in the training process. You can see that the generator starts out creating very noisy, fake images, but begins to converge to better representations as it trains (though, not perfect).

Below, you've been given a helper function for displaying generated samples based on the passed in training iteration.

In [39]:
import matplotlib.image as mpimg

# helper visualization code
def view_samples(iteration, sample_dir='samples_cyclegan'):
    
    # samples are named by iteration
    path_XtoY = os.path.join(sample_dir, 'sample-{:06d}-X-Y.png'.format(iteration))
    path_YtoX = os.path.join(sample_dir, 'sample-{:06d}-Y-X.png'.format(iteration))
    
    # read in those samples
    try: 
        x2y = mpimg.imread(path_XtoY)
        y2x = mpimg.imread(path_YtoX)
    except:
        print('Invalid number of iterations.')
    
    fig, (ax1, ax2) = plt.subplots(figsize=(18,20), nrows=2, ncols=1, sharey=True, sharex=True)
    ax1.imshow(x2y)
    ax1.set_title('X to Y')
    ax2.imshow(y2x)
    ax2.set_title('Y to X')
In [40]:
# view samples at iteration 100
view_samples(100, 'samples_cyclegan')
In [41]:
# view samples at iteration 1000
view_samples(1000, 'samples_cyclegan')
In [42]:
view_samples(2000, 'samples_cyclegan')

Further Challenges and Directions

  • One shortcoming of this model is that it produces fairly low-resolution images; this is an ongoing area of research; you can read about a higher-resolution formulation that uses a multi-scale generator model, in this paper.
  • Relatedly, we may want to process these as larger (say 256x256) images at first, to take advantage of high-res data.
  • It may help your model to converge faster, if you initialize the weights in your network.
  • This model struggles with matching colors exactly. This is because, if $G_{YtoX}$ and $G_{XtoY}$ may change the tint of an image; the cycle consistency loss may not be affected and can still be small. You could choose to introduce a new, color-based loss term that compares $G_{YtoX}(y)$ and $y$, and $G_{XtoY}(x)$ and $x$, but then this becomes a supervised learning approach.
  • This unsupervised approach also struggles with geometric changes, like changing the apparent size of individual object in an image, so it is best suited for stylistic transformations.
  • For creating different kinds of models or trying out the Pix2Pix Architecture, this Github repository which implements CycleGAN and Pix2Pix in PyTorch is a great resource.

Once you are satified with your model, you are ancouraged to test it on a different dataset to see if it can find different types of mappings!


Different datasets for download

You can download a variety of datasets used in the Pix2Pix and CycleGAN papers, by following instructions in the associated Github repository. You'll just need to make sure that the data directories are named and organized correctly to load in that data.

In [ ]: